package com.first.xiinn.action.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONObject;

import com.first.core.util.UUID;
import com.first.core.web.Constants;
import com.first.core.web.action.BaseAction;
import com.first.xiinn.model.BookStatistics;
import com.first.xiinn.model.User;
import com.first.xiinn.service.BookStatisticsService;
import com.opensymphony.xwork2.ActionContext;

public class BookStatisticsAction extends BaseAction{
	@Resource
	private BookStatisticsService bookStatisticsService;
	public static String getUserMenuDoc() {
		return USER_MENU_DOC;
	}

	private String bookid;
	public String getBookid() {
		return bookid;
	}

	public void setBookid(String bookid) {
		this.bookid = bookid;
	}

	private static final String USER_MENU_DOC = "_USER_MENU_DOC";

	public String save() {
		String success = "false";
		String msg="";
		ActionContext context = ActionContext.getContext();
		Map session = context.getSession();
		User user = (User) session.get(Constants.USER_SESSION_KEY);
		String type = ServletActionContext.getRequest().getParameter("statistics_type");
		HashMap map = new HashMap();
		map.put("book_id", this.bookid);
		map.put("type", type);
		try {
			if (user == null) {
				msg="您还没有登录";
			}else{
				map.put("user_id",user.getId());
				List list = this.bookStatisticsService.getStatisticsQuery(map);
				if(list!=null && list.size()>0){
					msg="您已经设置了该状态";
				}else{
					BookStatistics bs = new BookStatistics();
					bs.setId(UUID.getUUID());
					bs.setBookId(this.bookid);
					bs.setUserId(user.getId());
					bs.setType(type);
					bs.setSetingTime(new Timestamp(System.currentTimeMillis()));
					this.bookStatisticsService.saveStatistics(bs);
					success="true";
					msg="设置成功";
				}
			} 
		} catch (Exception e) {
			msg="系统错误";
			e.printStackTrace();
		}finally{
				JSONObject json = new JSONObject();
				json.put("success",success);
				json.put("msg",msg);
				HttpServletResponse response =  ServletActionContext.getResponse();
				try {
					response.setHeader("Pragma","No-cache");
					response.setDateHeader("Expires",0);
					response.setHeader("Cache-Control","no-cache"); 
					response.setCharacterEncoding("UTF-8");
					PrintWriter write = response.getWriter();
					write.write(json.toString());
					write.flush();
					write.close();
				} catch (IOException e) {
					e.getMessage();
				}
		}
		return "success";
	}

	public String getStatustucsByBookId() {
		return "success";
	}

}
